// pages/main/index.js
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar:'../../images/server_tong_all.png',
    username:'尚未登录',
    openid:'',
    userInfo:{},
    gender:'',
    birthday:'',
    email:'',
    isLoggedIn: false
  },
  //微信授权获取头像
  async handleLogin(ev){
    //1.获取头像
    let {avatarUrl}=ev.detail
    //上传到云存储
    const uploadRes=await wx.cloud.uploadFile({
      cloudPath:`avatars/${Date.now()}-${Math.floor(Math.random()*1000)}.png`,
      filePath:avatarUrl
    })
    //获取永久可以访问的url
    let {fileID}=uploadRes
    //调用云函数登录
    let res=await wx.cloud.callFunction({
      name:'login',
      data:{avatar:fileID}//直接使用云函数
    })
    console.log('登陆消息',res);
    //本地显示用户信息
    this.setData({
      avatar:fileID,
      username: res.result.userInfo.username,
      openid: res.result.openid,
      gender: res.result.userInfo.gender || '',
      birthday: res.result.userInfo.birthday || '',
      email: res.result.userInfo.email || '',
      isLoggedIn: true
    })
    //本地持久化存储用户信息
    wx.setStorage({
      key:'userinfo',
      data:{
        avatar: fileID,
        username: res.result.userInfo.username,
        openid: res.result.openid,
      }
    })
    getApp().userInfo=res.result
  },
 
  //修改昵称
  change_nickname() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    // 存储数据到全局变量
    app.globalData.tempUserInfo = {
      avatar: this.data.avatar,
      username: this.data.username,
      openid: this.data.openid,
      gender: this.data.gender||'', // 可选字段
      birthday: this.data.birthday||'', // 可选字段
      email: this.data.email||''     // 可选字段
    };
    // 跳转页面
    wx.navigateTo({
      url: '/package_main/pages/change-nickname/index'
    });
  },
  //退出登录
  handleLogout(){
    wx.removeStorage({
      key: 'userinfo',
    })
    this.setData({
      avatar:'../../images/server_tong_all.png',
      username:'尚未登录',
      openid:'',
      gender:'',
      birthday:'',
      email:'',
      isLoggedIn: false
    })
    console.log('退出登录成功');
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.getStorage({
      key:'userinfo',
      success:(res)=>{
        console.log('提取本地存储数据',res);
        this.setData({
          avatar: res.data.avatar,
          username: res.data.username,
          openid: res.data.openid,
          gender:res.data.gender || '',
          birthday:res.data.birthday || '',
          email:res.data.email || '',
          isLoggedIn: !!res.data.openid
        })
      }
    })
  },
})